package emas.server.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import emas.shared.Location;

public class WeatherDataManager {

	private static WeatherDataManager instance = new WeatherDataManager();

	private WeatherDataManager() {

	}

	private String getWeatherDataFromURL(String location) {
		URI url;
		String weatherIconURL = null;
		try {
			url = new URI("http://www.google.com/ig/api?weather="
					+ URLEncoder.encode(location, "UTF-8"));
			System.out.println("URL is: " + url.toString());
			URLConnection connection = url.toURL().openConnection();
			InputStream stream = connection.getInputStream();

			SAXBuilder builder = new SAXBuilder();
			Document document = builder.build(stream);
			Element rootElement = (Element) document.getRootElement()
					.getChildren().get(0);
			List<?> list = rootElement.getChildren();
			if (list.size() > 1) {
				Element currentCondition = (Element) list.get(1);
				List<?> currentConditionElementList = currentCondition
						.getChildren();
				Element weatherIcon = (Element) currentConditionElementList
						.get(4);
				weatherIconURL = "http://www.google.com"
						+ weatherIcon.getAttributeValue("data");
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JDOMException e) {
			e.printStackTrace();
		}

		return weatherIconURL;

	}

	public void addWeatherToLocations() {
		ArrayList<Location> locations = LocationManager.getInstance().getLocations();
		for (Location location : locations) {
			location.setWeatherImageURL(getWeatherDataFromURL(location.getAddress()));
		}
	}

	public static WeatherDataManager getInstance() {
		if (instance == null) {
			instance = new WeatherDataManager();
		}
		return instance;
	}
}
